"use client";

import { useState, useEffect } from "react";
import CarSearch from "@/components/CarSearch";
import CarCard from "@/components/CarCard";
import { CarSearchParams, carApiService, ApiResponse } from "@/services/api";
import { Car } from "@/data/cars";
import Link from "next/link";
import '@ant-design/v5-patch-for-react-19';
interface CarsApiResponse {
  cars: Car[];
  total: number;
  page: number;
  pageSize: number;
  stats: {
    totalCars: number;
    newCars: number;
    usedCars: number;
    brandsCount: number;
    avgPrice: number;
  };
}

interface StatsApiResponse {
  totalCars: number;
  newCars: number;
  usedCars: number;
  brandsCount: number;
  avgPrice: number;
}

export default function HomePage() {
  const [cars, setCars] = useState<Car[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [activeTab, setActiveTab] = useState<'all' | 'new' | 'used'>('all');
  const [stats, setStats] = useState({
    totalCars: 0,
    newCars: 0,
    usedCars: 0,
    brandsCount: 0,
    avgPrice: 0,
  });

  useEffect(() => {
    loadInitialData();
  }, []);

  const loadInitialData = async () => {
    try {
      setLoading(true);
      const [carsResponse, statsResponse] = await Promise.all([
        carApiService.searchCars({ page: 1, pageSize: 10 }),
        carApiService.getStats(),
      ]);

      if (carsResponse.code === 200) {
        setCars(carsResponse.data.cars);
        setHasMore(carsResponse.data.cars.length === 10);
      }

      if (statsResponse.code === 200) {
        setStats(statsResponse.data);
      }
    } catch (error) {
      console.error("加载数据失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const loadMoreCars = async () => {
    if (loadingMore || !hasMore) return;
    
    try {
      setLoadingMore(true);
      const nextPage = currentPage + 1;
      const response = await carApiService.searchCars({ 
        page: nextPage, 
        pageSize: 10,
        carType: activeTab === 'all' ? undefined : activeTab
      });

      if (response.code === 200) {
        setCars(prev => [...prev, ...response.data.cars]);
        setCurrentPage(nextPage);
        setHasMore(response.data.cars.length === 10);
      }
    } catch (error) {
      console.error("加载更多失败:", error);
    } finally {
      setLoadingMore(false);
    }
  };

  const handleTabChange = async (tab: 'all' | 'new' | 'used') => {
    setActiveTab(tab);
    setLoading(true);
    setCurrentPage(1);
    
    try {
      const response = await carApiService.searchCars({ 
        page: 1, 
        pageSize: 10,
        carType: tab === 'all' ? undefined : tab
      });

      if (response.code === 200) {
        setCars(response.data.cars);
        setHasMore(response.data.cars.length === 10);
      }
    } catch (error) {
      console.error("切换分类失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async (searchParams: CarSearchParams) => {
    try {
      setLoading(true);
      const response = await carApiService.searchCars({
        ...searchParams,
        page: 1,
        pageSize: 10,
        carType: activeTab === 'all' ? undefined : activeTab
      });

      if (response.code === 200) {
        setCars(response.data.cars);
        setCurrentPage(1);
        setHasMore(response.data.cars.length === 10);
      }
    } catch (error) {
      console.error("搜索失败:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-gray-100">
      {/* 企业级头部区域 */}
      <div className=" bg-[linear-gradient(to_right,#EC302F,#F26E6D)]  text-white">
        <div className="max-w-7xl mx-auto px-4 py-8">
            {/* <h1 className="text-5xl md:text-6xl font-bold mb-6 leading-tight">
              专业汽车展示平台
            </h1> */}
            <p className="text-center text-xl mb-8 max-w-4xl mx-auto opacity-80 leading-relaxed">
              全球领先的汽车进出口贸易平台，为您提供优质的新车、二手车展示服务
            </p>
          {/* 搜索和筛选区域 - 居中搜索框 */}
          <div className="max-w-7xl mx-auto px-4">
            <div className="flex justify-center mb-8">
              <div className="w-full max-w-4xl">
                <CarSearch onSearch={handleSearch} />
              </div>
            </div>
          </div>
        </div>

        {/* 加载状态 */}
        {loading && (
          <div className="text-center py-12">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
            <p className="mt-4 text-gray-600">正在加载车辆数据...</p>
          </div>
        )}

        {/* 企业级车辆列表 */}
        {!loading && (
          <>
            <div className="mx-20">
              {/* Tabs分类 */}
              <div className="flex justify-center mb-8">
                <div className="bg-white rounded-full p-1 shadow-lg">
                  <div className="flex space-x-1">
                    <button
                      onClick={() => handleTabChange('all')}
                      className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
                        activeTab === 'all'
                          ? 'bg-blue-600 text-white shadow-md'
                          : 'text-gray-600 hover:text-blue-600 hover:bg-gray-100'
                      }`}
                    >
                      全部 ({stats.totalCars})
                    </button>
                    <button
                      onClick={() => handleTabChange('new')}
                      className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
                        activeTab === 'new'
                          ? 'bg-green-600 text-white shadow-md'
                          : 'text-gray-600 hover:text-green-600 hover:bg-gray-100'
                      }`}
                    >
                      新车 ({stats.newCars})
                    </button>
                    <button
                      onClick={() => handleTabChange('used')}
                      className={`px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 ${
                        activeTab === 'used'
                          ? 'bg-orange-600 text-white shadow-md'
                          : 'text-gray-600 hover:text-orange-600 hover:bg-gray-100'
                      }`}
                    >
                      二手车 ({stats.usedCars})
                    </button>
                  </div>
                </div>
              </div>

              {cars.length === 0 ? (
                <div className="text-center py-16 bg-white rounded-2xl shadow-lg">
                  <div className="text-8xl mb-6">🚗</div>
                  <h4 className="text-2xl font-semibold text-gray-900 mb-4">
                    暂无匹配车辆
                  </h4>
                  <p className="text-gray-600 text-lg">
                    请尝试调整筛选条件或搜索其他关键词
                  </p>
                </div>
              ) : (
                <>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4">
                    {cars.map((car) => (
                      <CarCard key={car.id} car={car} />
                    ))}
                  </div>
                  
                  {/* 加载更多按钮 */}
                  {hasMore && (
                    <div className="text-center mt-8">
                      <button
                        onClick={loadMoreCars}
                        disabled={loadingMore}
                        className="bg-blue-600 text-white px-8 py-3 rounded-full font-medium hover:bg-blue-700 transition-colors duration-200 disabled:opacity-50 disabled:cursor-not-allowed mr-4"
                      >
                        {loadingMore ? (
                          <span className="flex items-center">
                            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                            加载中...
                          </span>
                        ) : (
                          '加载更多'
                        )}
                      </button>
                      <Link
                        href="/cars"
                        className="bg-green-600 text-white px-8 py-3 rounded-full font-medium hover:bg-green-700 transition-colors duration-200 inline-block"
                      >
                        查看更多
                      </Link>
                    </div>
                  )}
                </>
              )}
            </div>
          </>
        )}
      </div>

      {/* 底部信息 */}
      <div className="bg-gray-900 text-white mt-12">
        <div className="max-w-7xl mx-auto px-4 py-8">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            <div>
              <h4 className="text-lg font-semibold mb-4">关于我们</h4>
              <p className="text-gray-400">
                专业汽车展示平台致力于为全球用户提供最优质的汽车交易服务，
                涵盖新车、二手车进出口贸易。
              </p>
            </div>
            <div>
              <h4 className="text-lg font-semibold mb-4">联系我们</h4>
              <p className="text-gray-400">客服热线: 400-123-4567</p>
              <p className="text-gray-400">邮箱: service@autoshow.com</p>
            </div>
            <div>
              <h4 className="text-lg font-semibold mb-4">服务承诺</h4>
              <p className="text-gray-400">
                100%真实车源 · 专业检测认证 · 7天无忧退换 · 全程交易保障
              </p>
            </div>
          </div>
          <div className="border-t border-gray-800 mt-8 pt-8 text-center text-gray-400">
            <p>© 2025 专业汽车展示平台. 保留所有权利.</p>
          </div>
        </div>
      </div>
    </div>
  );
}
